package edu.biwu.req;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;

/**
 * HttpServletRequest中获取请求体的方法:
 *    public String getParameter(String name):适用于一个参数对应一个值,后端根据前端name的值获取对应的值
 *    public String[] getParameterValues(String name):使用于一个参数对应多个值,后端根据前端的name的值获取该参数对应的所有值
 *    public String[] getParameterValues(String name):将页面提交的所有参数封装到一个Map中,Map中数据的格式
 *                                                    key:提交的name值
 *                                                    value:name对应一个或多个值,将这些值放到一个字符串数组中
 */
@WebServlet("/req/demo03")
public class RequestDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("username"));
        System.out.println(request.getParameter("password"));
        System.out.println(request.getParameter("gender"));

//        String[] hobbies = request.getParameterValues("hobby");
//        for (String hobby : hobbies)
//        {
//            System.out.println(hobby);
//        }
        Stream.of(request.getParameterValues("hobby")).forEach(System.out::println);

        System.out.println("-------------------------------------------------------");

//        Map<String, String[]> parameterMap = request.getParameterMap();
//        for (Map.Entry<String, String[]> entry:parameterMap.entrySet()){
//        System.out.println(entry.getKey()+"="+ Arrays.toString(entry.getValue()));
//        }
        request.getParameterMap().forEach((key, value)-> System.out.println(key+"="+ Arrays.toString(value)));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
